package com.grj.es.service.impl;

import com.grj.es.entity.Shop;
import com.grj.es.repostory.ShopRepository;
import com.grj.es.service.ShopService;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.builders.PointBuilder;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ShopServiceImpl implements ShopService {


    @Resource
    private ShopRepository shopRepository;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Override
    public List<Shop> search(String keyword) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 以某点为中心，搜索指定范围
        GeoDistanceQueryBuilder distanceQueryBuilder = new GeoDistanceQueryBuilder("location");
        distanceQueryBuilder.point(116, 23);
        //查询单位：km
        distanceQueryBuilder.distance(10, DistanceUnit.KILOMETERS);
        boolQueryBuilder.filter(distanceQueryBuilder);
//        if (StringUtils.isNotEmpty(keyword)) {
//            boolQueryBuilder.must(
//                    QueryBuilders.boolQuery().should(QueryBuilders.wildcardQuery("content", "*" + keyword + "*"))
//                            .should(QueryBuilders.wildcardQuery("name", "*" + keyword + "*")));
//        }
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        // 按距离升序
        nativeSearchQueryBuilder.withSort(new GeoDistanceSortBuilder("location", 116, 23).unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC));
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 10));
        SearchHits<Shop> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), Shop.class);

        return search.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
    }
}
